<script setup lang="tsx">
import { ref } from 'vue';
import { $t } from '@/locales';
import type { ApiStateInput, ApiSysEmailSendConfigOut, ApiSysEmailSendConfigQuery, ApiUserOut, ApiUserQuery } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import OperateModal from './modules/operate-modal.vue';
import Search from './modules/search.vue';
import { SysemailsendconfigApi } from '@/api-services/apis/sysemailsendconfig-api';
import { ElButton, ElPopconfirm, ElSwitch, ElTag, SwitchProps } from 'element-plus';

const { tableWrapperRef, scrollConfig } = useTableScroll();


// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysEmailSendConfigQuery) =>
  fetchTableQuery<ApiSysEmailSendConfigQuery, ApiSysEmailSendConfigOut>(params,
    (internalParams: ApiSysEmailSendConfigQuery) =>
      getAPI(SysemailsendconfigApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});

const {
  columns,
  columnChecks,
  tableSize,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  size: "small",
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: '',
    startDate: undefined,
    endDate: undefined
  },
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      minWidth: 130
    },

    {
      //SMTP服务器
      prop: 'emailSmtpHost',
      //dataIndex: 'emailSmtpHost',
      label: $t('page.emailManage.emailConfig.emailSmtpHost'),
      align: 'center',
      minWidth: 100
    },
    {
      //邮件服务器Smtp端口
      prop: 'emailSmtpPort',
      //dataIndex: 'emailSmtpPort',
      label: $t('page.emailManage.emailConfig.emailSmtpPort'),
      align: 'center',
      minWidth: 100
    },
    {
      //邮箱账号
      prop: 'emailAccount',
      //dataIndex: 'emailAccount',
      label: $t('page.emailManage.emailConfig.emailAccount'),
      align: 'center',
      minWidth: 100
    },
    {
      //发送者显示名
      prop: 'emailDisplayName',
      //dataIndex: 'emailDisplayName',
      label: $t('page.emailManage.emailConfig.emailDisplayName'),
      align: 'center',
      minWidth: 100,
      hide: true
    },
    // 是否启用
    {
      prop: 'isEnable',
      //dataIndex: 'isEnable',
      label: $t('page.manage.common.isEnable'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isEnable === null) {
          return '';
        }
        const handleSwitchChange = async (checked: boolean | string | number) => {
          if (!record.id) {
            return;
          }
          // 提交请求
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: true
          };
          const [err, res] = await feature(getAPI(SysemailsendconfigApi).setIsEnable(record.id, Boolean(checked)));
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: false
          };
          queryDone(err, async () => {
            if (res?.data.data) {
              record.isEnable = Boolean(checked);
            } else {
              window.$message?.error($t('common.failed'));
            }
          });
        };
        return (
          <ElSwitch
            modelValue={record.isEnable}
            onChange={(value: SwitchProps['modelValue']) => handleSwitchChange(value as boolean | string | number)}
            loading={loadingStates.value[record.id!] || false}
          ></ElSwitch>
        );
      }
    },

    {
      prop: 'isDefault',
      //dataIndex: 'isDefault',
      label: $t('page.emailManage.emailConfig.isDefault'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isDefault === null) {
          return '';
        }
        if (record.isDefault == true) {
          return <ElTag type="success">{$t('common.yesOrNo.yes')}</ElTag>
        } else {
          return <ElTag type="danger">{$t('common.yesOrNo.no')}</ElTag>
        }
      }
    },


    {
      //是否启用SSL加密
      prop: 'emailIsSsl',
      //dataIndex: 'emailIsSsl',
      label: $t('page.emailManage.emailConfig.emailIsSsl'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.emailIsSsl === null) {
          return '';
        }
        if (record.emailIsSsl == true) {
          return <ElTag type="success">{$t('common.yesOrNo.yes')}</ElTag>
        } else {
          return <ElTag type="danger">{$t('common.yesOrNo.no')}</ElTag>
        }
      }
    },
    {
      //备注
      prop: 'remark',
      //dataIndex: 'remark',
      label: $t('page.manage.common.remark'),
      align: 'center',
      minWidth: 200
    },


    {
      //创建时间
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    // 创建人
    {
      prop: 'creatorUserName',
      //dataIndex: 'creatorUserName',
      label: $t('common.creatorUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    // 修改时间
    {
      prop: 'updateTime',
      //dataIndex: 'updateTime',
      label: $t('common.updateTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    // 修改人
    {
      prop: 'updateUserName',
      //dataIndex: 'updateUserName',
      label: $t('common.updateUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    // 操作
    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      minWidth: 230,
      fixed: 'right',
      formatter: record => (
        <div class="flex-center gap-8px">
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id!)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const { isVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);
const edit = (id: number | undefined) => {
  if (!id) return;
  // console.log(id);
  handleEdit(id);
};
const handleDelete = async (id: number) => {
  const ids = [];

  // 提交请求
  const [err, res] = await feature(getAPI(SysemailsendconfigApi).batchDelete(id.toString()));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      window.$message?.error('删除失败');
    }
  });
};
const handleBatchDeleted = async () => {
  if (checkedRowKeys.value == undefined || checkedRowKeys.value.length == 0) {
    return;
  }
  const ids = checkedRowKeys.value?.join(',');

  // 提交请求
  const [err, res] = await feature(getAPI(SysemailsendconfigApi).batchDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      window.$message?.error('删除失败');
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>

    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.emailManage.emailConfig.title') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" @add="handleAdd"
            @delete="handleBatchDeleted" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>

      <OperateModal v-model:visible="isVisible" :operate-type="operateType" :row-data="editingData"
        @submitted="getDataByPage" />
    </ElCard>
  </div>
</template>

<style scoped></style>
